import asyncio
from base64 import b64encode
import base64
import logging
from typing import AsyncGenerator
import websockets
import json
from asr_server import ASRCallbacks, ASRResult, ASRServer, ASRConfig

# ASR配置 - 替换为你的实际配置
CONFIG  = ASRConfig(
        app_id="f4b3bfd8",
        api_key="3f6b034a6397fab4d4478345f42340e2",
        api_secret="MDdhM2I3NjM0NjViOTVlY2JkZjQ5NTZj"
    )

class ASRFileServer:
    config = None

    @staticmethod
    async def set_file(file,path,chunk_size=8000)->AsyncGenerator[ASRResult,None]:
        chunck_limit = chunk_size
        
        if not file and not path:
            return
        # if path:
        #     file = open(path,"rb")
        client_id = id(file)
        server = ASRServer.create_asr_server(ASRFileServer.config,client_id,chunck_limit)
        server.create_asr_connection()
        async def feed_audio(audio_file, chunk_size: int = 1280):
            path2 = '/home/loby/音乐/20250410022312-Jx6FbN-base65.b642'
            # Write raw audio data to file
            with open(path2, 'rb') as f2:
                while True:
                    try:
                        chunk = f2.read(chunk_size*10)
                        if not chunk:
                            break
                        # f2.write(chunk)
                        
                        # Base64 encode only for server communication
                        base64_chunk = chunk.decode() #base64.b64encode(chunk).decode("utf-8")
                        await server.write_audio(None, base64str=base64_chunk)
                    except Exception as e:
                        print(e)
                        break
        await feed_audio(file,chunck_limit)
        return server.process_results()
        
async def result_deeling(response: AsyncGenerator[ASRResult, None]):
    async for result in response:
        print(result)
        
from werkzeug.datastructures import FileStorage
from werkzeug.utils import secure_filename
    
async def main():
    ASRFileServer.config = CONFIG
    path = '/home/loby/音乐/20250410022312-Jx6FbN.pcm'
    try:
        # with open(path, 'rb') as f:
        response = await ASRFileServer.set_file(None,path)
        async for result in response:
            print(result)
    except asyncio.CancelledError:
        print("Shutting down gracefully...")
    except Exception as e:
        print(f"Error: {e}")
    finally:
        print("Cleanup complete")

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nServer stopped by user")
